package com.kakaxi.mybilibili.module.search.view;

import android.graphics.drawable.AnimationDrawable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kakaxi.mybilibili.R;
import com.kakaxi.mybilibili.adapter.entity.HorizontalVideoMultiItem;
import com.kakaxi.mybilibili.adapter.pager.BaseFragmentPagerAdapter;
import com.kakaxi.mybilibili.base.BaseFragment;
import com.kakaxi.mybilibili.base.NavigationActivity;
import com.kakaxi.mybilibili.bean.EventBusObject;
import com.kakaxi.mybilibili.module.search.presenter.ISearchPresenter;
import com.kakaxi.mybilibili.module.search.presenter.SearchPresenter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 搜索活动类
 * Created by kakaxi on 16/11/24.
 */

public class SearchActivity extends NavigationActivity implements ISearchView {

    /** 浮动布局 **/
    @BindView(R.id.llayout_search_float_content)
    ViewGroup mFloatContent;
    /** 浮动输入框 **/
    @BindView(R.id.edt_search_float_input)
    EditText mFloatInputEdt;
    /** 浮动后退 **/
    @BindView(R.id.ibtn_search_float_back)
    ImageButton mBackIBtn;
    /** 清除按钮 **/
    @BindView(R.id.ibtn_search_float_clear)
    ImageButton mClearIBtn;
    /** 遮罩层 **/
    @BindView(R.id.view_search_black_mask)
    View mMaskView;

    /** 在底部的输入框 **/
    @BindView(R.id.edt_search_floor_input)
    EditText mFloorInputEdt;

    @BindView(R.id.llayout_search_content)
    LinearLayout mContentLayout;
    /** 标签布局 **/
    @BindView(R.id.tablayout_search_tab)
    TabLayout mTabLayout;
    /** 滑动布局 **/
    @BindView(R.id.vp_search_pager)
    ViewPager mViewPager;

    @BindView(R.id.img_search_floor_holder)
    ImageView mHolderImg;

    @BindView(R.id.ibtn_search_float_action)
    ImageButton mActionIBtn;

    /** 搜索类型 **/
    public static final String EXTRA_TYPE = "type";
    /** 搜索关键词 **/
    public static final String EXTRA_KEYWORD = "keyword";

    /** 视频类型 **/
    public static final int TYPE_VIDEO = 1;
    /** 直播类型 **/
    public static final int TYPE_LIVE = 2;

    /** 当前搜索类型 **/
    private int mType;

    /** 是否已经查找过了 **/
    private boolean mHasSearch;

    private ISearchPresenter mPresenter;

    /** 动画 **/
    private AnimationDrawable mAnimation;

    @Override
    protected int getCurrentMenuItemId() {
        return R.menu.menu_nav;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_search;
    }

    @Override
    protected void setupViews() {
        ButterKnife.bind(this);

        // 初始化输入框
        initInputEdt();
    }

    @Override
    protected void initData() {
        mPresenter = new SearchPresenter(this);

        mType = getIntent().getIntExtra(EXTRA_TYPE, 0);
        if (mType == 0) {
            toastHandler("缺少类型参数");
            finish();
            return;
        }

        initTabPagerData();

        // 打开直接搜索处理
        String keyword = getIntent().getStringExtra(EXTRA_KEYWORD);
        if (keyword != null && !keyword.trim().isEmpty()) {
            mFloatInputEdt.setText(keyword);
            mActionIBtn.performClick();
        }

    }

    /**
     * 初始化标签和滑动布局的数据
     */
    private void initTabPagerData() {
        List<BaseFragment> fragmentList = new ArrayList<>();
        if (mType == TYPE_VIDEO) {
            fragmentList.add(SearchVideoFragment.newInstance());
        } else if (mType == TYPE_LIVE) {

        }
        mViewPager.setAdapter(new BaseFragmentPagerAdapter<>(getSupportFragmentManager(),
                fragmentList));
        mTabLayout.setupWithViewPager(mViewPager);
    }

    /**
     * 设置浮动查询的可见度
     *
     * @param visibility 是否可见
     */
    private void setFloatSearchVisibility(int visibility) {
        mFloatContent.setVisibility(visibility);
        mMaskView.setVisibility(visibility);
    }

    /**
     * 设置搜索正文的显示
     *
     * @param isShow 是否展示
     */
    private void setSearchContentVisibility(boolean isShow) {
        if (mAnimation == null) {
            mAnimation = (AnimationDrawable) mHolderImg.getBackground();
        }
        if (isShow) {
            mContentLayout.setVisibility(View.VISIBLE);

            mAnimation.stop();
            mHolderImg.setVisibility(View.GONE);
        } else {
            mContentLayout.setVisibility(View.INVISIBLE);

            mAnimation.start();
            mHolderImg.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 点击事件
     *
     * @param v 点击控件
     */
    @OnClick({R.id.view_search_black_mask,
            R.id.ibtn_search_float_clear,
            R.id.llayout_search_floor_content,
            R.id.edt_search_floor_input,
            R.id.ibtn_search_float_back,
            R.id.ibtn_search_floor_back,
            R.id.ibtn_search_float_action})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_search_float_back: // 浮动后退
            case R.id.view_search_black_mask: {// 遮罩层
                hideSoftInput(mFloatInputEdt);
                break;
            }
            case R.id.ibtn_search_float_clear: { // 清除按钮
                mFloatInputEdt.setText("");
                break;
            }
            case R.id.llayout_search_floor_content: // 底部输入框内容
            case R.id.edt_search_floor_input: { // 底部输入框
                setFloatSearchVisibility(View.VISIBLE);
                showSoftInput(mFloatInputEdt);
                break;
            }
            case R.id.ibtn_search_floor_back: { // 底部后退
                finish();
                break;
            }
            case R.id.ibtn_search_float_action: { // 搜索
                doSearch();
                break;
            }
        }
    }

    /**
     * 搜索操作
     */
    private void doSearch() {
        String keyword = mFloatInputEdt.getText().toString();
        if (!keyword.trim().isEmpty()) {
            hideSoftInput(mFloatInputEdt);
            // 设置为读取动画
            if (!mHasSearch) {
                mHolderImg.setImageDrawable(null);
                mHolderImg.setBackgroundResource(R.drawable.anim_search_loading);
                mHasSearch = true;
            }
            mPresenter.searchVideoData(keyword, 1);
        }
    }

    /**
     * 初始化输入框
     */
    private void initInputEdt() {
        mFloatInputEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    setFloatSearchVisibility(View.VISIBLE);
                } else {
                    setFloatSearchVisibility(View.INVISIBLE);
                }
            }
        });
        mFloatInputEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mClearIBtn.setVisibility(View.VISIBLE);
                } else {
                    mClearIBtn.setVisibility(View.INVISIBLE);
                }
                // 底部输入框内容跟着变
                mFloorInputEdt.setText(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        // 键盘右下角按钮点击操作
        mFloatInputEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event
                        .getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    doSearch();
                    return true;
                }
                return false;
            }
        });
        mFloatInputEdt.requestFocus();
    }

    @Override
    public void showSearchVideo(List<HorizontalVideoMultiItem> videoMultiItemList) {
        if (videoMultiItemList != null) {
            EventBusObject object = new EventBusObject(EventBusObject
                    .EVENT_SEARCH_VIDEO_FRAG_SHOW_SEARCH, videoMultiItemList);
            EventBus.getDefault().post(object);
            mContentLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showLoading() {
        setSearchContentVisibility(false);
    }

    @Override
    public void hideLoading() {
        setSearchContentVisibility(true);
    }

    @Override
    public void showEmptyView() {

    }

    @Override
    public void showMessage(String message) {
        toastHandler(message);
    }
}
